var createError = require('http-errors');
var express = require('express');
var path = require('path');
var fs = require('fs');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var http = require('http');
var colors = require('colors');
var multer = require('multer'); //multer - node.js 中间件，用于处理 enctype="multipart/form-data"（设置表单的MIME编码）的表单数据。
const log = require('./src/libs/log').logger;

const {
  SuccessModel,
  ErrorModel
} = require('./src/libs/resmodel')


var app = express();


//处理跨域
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*'); //这个表示任意域名都可以访问，这样写不能携带cookie了。req.headers['origin']
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');//设置方法
  res.header('Access-Control-Allow-Credentials', true);//允许携带cookie 如果前端配置了这个withCredentials=true，后段设置Access-Control-Allow-Origin不能为 " * ",必须是你的源地址
  if (req.method == 'OPTIONS') {
    res.send(200); // 意思是，在正常的请求之前，会发送一个验证，是否可以请求。
  } else {
    next();
  }
})

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// app.use(express.static(path.join(__dirname, 'public')));
app.use(multer({ dest: './public/' }).any('files',10))// 通过配置multer的dest属性， 将文件储存在项目下的tmp文件中
app.use('/statics', express.static('statics'));
// app.post('/ossfile/upload', function (req, res) {
//  try {
//   console.log('--------/ossfile/upload-body-',req.body)
//   console.log('--------/ossfile/upload-body.type-',req.body.type)
//   console.log('--------/ossfile/upload-files-',req.files)
//   let old = req.files[0].path //获取path:
//   console.log('--------/ossfile/upload--',old)
//   let newpath = req.files[0].path + path.parse(req.files[0].originalname).ext;
//   console.log('--------/ossfile/upload-newpath-',newpath)
//   fs.renameSync(old, newpath)
//  } catch (error) {
//   console.log('--------/ossfile/upload--error',error)
//  }
// });


require('./src/libs/boot')(app);
require('./src/libs/schedule')();

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  // res.locals.message = err.message;
  // res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json(new ErrorModel(err.message));
});

// 捕获可以让系统崩溃的错误，避免进程反复重启
process.on('uncaughtException', function (err) {
  err.name = "UncaughtExceptionError";
  console.log('Caught exception: ' + err.stack);
});

// 启动服务器
http.createServer(app).listen(3000, function () {
  if (process.env.http_proxy) {
    console.log(colors.green('Using proxy:'), colors.green(process.env.http_proxy));
  }
  console.log('redspider-appserver port:3000已启动!!')
  log.info('redspider-appserver port:3000已启动!!')
}).on('close', function () {
  console.log(colors.red('terminating server'));
  log.info(colors.red('terminating server'));
});
